# -*- coding: utf-8 -*-
"""
代码场景模板 - 专门用于代码展示
"""

from typing import Any, Dict, List, Optional
from pathlib import Path

from .base_template import BaseSceneTemplate


class CodeSceneTemplate(BaseSceneTemplate):
    """代码场景模板"""

    def __init__(
        self,
        title: str = "",
        code: str = "",
        language: str = "python",
        audio_duration: float = 0.0,
        subtitle_file: Optional[Path] = None,
        theme=None,
        show_line_numbers: bool = True,
    ):
        """
        初始化代码场景

        Args:
            title: 标题
            code: 代码内容
            language: 编程语言
            audio_duration: 音频时长
            subtitle_file: 字幕文件
            theme: 主题
            show_line_numbers: 是否显示行号
        """
        super().__init__(title, code, audio_duration, subtitle_file, theme)
        self.code = code
        self.language = language
        self.show_line_numbers = show_line_numbers

    def create_content(self, scene) -> Dict[str, Any]:
        """
        创建代码内容

        Args:
            scene: Manim场景对象

        Returns:
            包含标题和代码的字典
        """
        content = {}

        # 创建标题
        if self.title:
            title_style = self.get_style("title")
            title_obj = scene.Text(
                self.title,
                font_size=title_style["font_size"],
                color=title_style["color"],
                font=title_style["font"],
            )
            title_obj.to_edge(scene.UP, buff=self.get_position("safe_margin_y"))
            content["title"] = title_obj

        # 创建代码
        if self.code:
            code_style = self.get_style("code")
            code_lines = self.code.split("\n")

            # 创建代码块
            code_group = scene.VGroup()

            for i, line in enumerate(code_lines):
                # 处理行号
                if self.show_line_numbers:
                    line_number = scene.Text(
                        f"{i+1:3d} ",
                        font="Consolas",
                        font_size=20,
                        color=self.get_color("text_secondary"),
                    )
                    code_line = scene.Text(
                        line,
                        font="Consolas",
                        font_size=code_style["font_size"],
                        color=code_style["color"],
                    )
                    line_group = scene.HGroup(line_number, code_line)
                else:
                    line_group = scene.Text(
                        line,
                        font="Consolas",
                        font_size=code_style["font_size"],
                        color=code_style["color"],
                    )

                code_group.add(line_group)

            # 定位代码块
            code_group.center()
            content["code"] = code_group

        return content

    def animate_content(self, scene, content: Dict[str, Any]) -> None:
        """
        动画代码内容

        Args:
            scene: Manim场景对象
            content: 内容字典

        Returns:
            None
        """
        animations = []

        # 标题动画
        if "title" in content:
            title = content["title"]
            animations.append(scene.FadeIn(title, run_time=0.5))

        # 代码动画
        if "code" in content:
            code = content["code"]
            # 逐行显示代码
            lines = code
            if hasattr(code, "submobjects"):
                for line in code.submobjects:
                    animations.append(scene.FadeIn(line, run_time=0.2))
            else:
                animations.append(scene.FadeIn(code, run_time=0.5))

        # 播放所有动画
        for anim in animations:
            scene.play(anim)

            # 如果使用了TimeScaler，等待相应时间
            if self.scaler:
                self.scaler.current_time += anim.run_time
